<template>
	<coreshop-navbar :isBack="false" mode="left" title="购物车"> </coreshop-navbar>
	<view class="content-box p-25 page-bg">
		<view class="cart-box" v-if="state.cartList.length > 0">
			<view class="all-select" :style="{ 'top': `${statusBarHeight}px` }">
				<view class="icon-box" @click="hanldeChangeAllSelect">
					<image class="icon" v-if="state.isAllSelect"
						:src="handleStaticResources('/static/images/icon/cart-select-on.png')"></image>
					<image class="icon" v-else :src="handleStaticResources('/static/images/icon/cart-select.png')">
					</image>
					<text class="tit">全选</text>
				</view>
				<view class="manage" @click="handleChangeManage">
					<text v-if="state.isManage">管理</text>
					<text v-else>完成</text>
				</view>
			</view>

			<view class="data-box">
				<view class="item-box" v-for="item, index in state.cartList" :key="item.id">
					<view class="item-content">
						<view class="icon-box" @click="hanldeSelectGoods(index)">
							<image class="icon" v-if="item.select"
								:src="handleStaticResources('/static/images/icon/cart-select-on.png')"></image>
							<image class="icon" v-else
								:src="handleStaticResources('/static/images/icon/cart-select.png')">
							</image>
						</view>
						<view class="img-box" @click="hanldeSelectGoods(index)">
							<image class="img" :src="item?.products?.images"></image>
							<view class="give-point" v-if="isShowBuyGivePoint && item?.products?.points > 0">
								(赠送{{ item?.products?.points }}{{ shopConfigStore?.config?.pointShowName }})
							</view>
						</view>
						<view class="msg-box">
							<view class="name"
								@click="handleRouteNavigateTo(`/pages/goods/detail?id=${item?.products?.goodsId}`)">
								{{ item?.products?.name }}
							</view>
							<view class="desc"
								@click="handleRouteNavigateTo(`/pages/goods/detail?id=${item?.products?.goodsId}`)">
								{{ item?.products?.spesDesc }}
							</view>
							<view class="price-box">
								<view class="price">
									<text class="symbol">￥</text>
									<text>{{ item?.products?.price }}</text>
								</view>
								<view class="setop-box" v-if="state.isManage">
									<uv-number-box v-model="item.nums" inputWidth="27" button-size="27"
										:max="item?.products?.stock"
										@change="handleChangeGoodsNum($event,item)"></uv-number-box>
								</view>
								<view class="setop-box" v-else @click="hanlderDeleteSingleGoods(item, index)">
									<uv-icon name="trash" color="#CBCBCB" size="24"></uv-icon>
								</view>
							</view>
						</view>
					</view>
					<view class="point-redemption-price"
						v-if="isShowPointRedemptionPrice && item?.products?.pointsDeduction > 0">
						<text class="tit">{{ shopConfigStore?.config?.pointShowName }}兑换价：</text>
						<text>{{ shopConfigStore?.config?.pointDiscountedProportion * item?.products?.pointsDeduction
                            }}{{ shopConfigStore?.config?.pointShowName }}</text> +
						<text>￥{{ item?.products?.price - item?.products?.pointsDeduction < 0 ? 0 :
                            parseFloat(String(item?.products?.price -
                                item?.products?.pointsDeduction)).toFixed(2)}}</text>
					</view>
					<view class="tag-box" v-if="item?.products?.promotionList">
						<view class="tag" v-for="cell, cellIndex in item?.products?.promotionList" :key="cellIndex">
							<uv-tags :text="cell.name" type="success" plain size="mini">1</uv-tags>
						</view>
					</view>
				</view>
			</view>
		</view>
		<view v-else class="empty-box">
			<coreshop-empty text="您的购物车空空如也" mode="cart"></coreshop-empty>
			<view class="btn-empty" @click="handleRouteSwitchTab(RouteSwitchTabEnum.classify)">随便逛逛</view>
		</view>

		<view class="btn-box" v-if="state.cartList.length > 0">
			<view :class="['btn-position', { 'on': !state.isManage }]">
				<view class="btn-buy">
					<view class="price">
						<view>商品总价：</view>
						<view class="point-box">
							<view class="num"><text class="symbol">￥</text>{{ state.total }}</view>
							<view class="point" v-if="isShowPointRedemptionPrice && state.pointShowMoney > 0">
								<text>{{ shopConfigStore.config.pointShowName }}兑换价：</text>
								<text class="tit">{{ state.pointShowText }}</text>
							</view>
						</view>
					</view>
					<view class="buy" @click="handleGoToBuy">去结算</view>
				</view>
				<view class="btn-manage">
					<view class="all-delete" @click="hanlderDeleteAllGoods">移除全部</view>
					<view class="delete" @click="hanlderDeleteSomeGoods">移除</view>
				</view>
			</view>
		</view>
		<uv-loading-page :loading="loading" loading-text="加载中..." color="#d33123" loadingColor="#d33123"
			font-size="24rpx" bgColor="rgba(255, 255, 255, 0.2)"></uv-loading-page>
	</view>
</template>

<script setup lang="ts">
	import { reactive, nextTick, computed, ref } from 'vue';
	import { onShow, onPullDownRefresh } from '@dcloudio/uni-app';
	import { handleStaticResources, hanldeShowModal, handleRouteSwitchTab, handleRouteNavigateTo, handleShowToast } from '@/core/utils';
	import { queryCartList, deleteGoodsSingle, deleteGoodsSome, setCartProductNum } from '@/core/api';
	import type { Response, CartListType, ShopConfigStoreType } from '@/core/models';
	import { useShopConfigStore } from '@/core/store';
	import {
		OpenPointEnum, PointExchangeModelEnum, ShowPointExchangePriceEnum, RouteSwitchTabEnum,
		PointsGiveModeEnum, ShowPointsGiveMsgEnum,
	} from '@/core/enum';
	import { useLoadingFn, useSystemInfo } from '@/core/hooks';
	import { UserToken } from '@/core/consts'

	// 获取项目配置
	const shopConfigStore : ShopConfigStoreType = useShopConfigStore();
	// 获取自定义导航栏高度
	const { statusBarHeight } = useSystemInfo();
	const loading = ref(true);
	const state = reactive<{
		isManage : boolean,
		isAllSelect : boolean,
		cartList : Array<CartListType>;
		total : number;
		pointShowMoney : number;
		pointShowText : string;
	}>({
		isManage: true,
		isAllSelect: true,
		cartList: [],
		total: 0,
		pointShowMoney: 0,
		pointShowText: "",
	})

	const handleuGetCartList = useLoadingFn(getCartList, loading);


	/** 是否显示积分兑换价格 */
	const isShowPointRedemptionPrice = computed(() => {
		return shopConfigStore.config.pointSwitch == OpenPointEnum.yes &&
			shopConfigStore.config.pointExchangeModel == PointExchangeModelEnum.single &&
			shopConfigStore.config.pointShowExchangePrice == ShowPointExchangePriceEnum.yes;
	})

	/** 是否显示购买送积分 */
	const isShowBuyGivePoint = computed(() => {
		return shopConfigStore.config.pointSwitch == OpenPointEnum.yes &&
			shopConfigStore.config.pointGetModel == PointsGiveModeEnum.single &&
			shopConfigStore.config.pointShowPoint == ShowPointsGiveMsgEnum.yes;
	})

	onShow(() => {
		getCart();
	})

	onPullDownRefresh(async () => {
		await getCart();
		uni.stopPullDownRefresh();
	});

	async function getCart() {
		state.isManage = true;
		if (uni.getStorageSync(UserToken)) { 
			handleuGetCartList();
		}else{
			loading.value = false;
		} 
	}


	/** 获取购物车数据 */
	async function getCartList() {
		const cartList : Response<any> = await queryCartList({
			display: "all",
			ids: ""
		})
		if (cartList.status) {
			state.cartList = cartList?.data?.list?.map((item : CartListType) => {
				item['select'] = true;
				return item;
			});
			state.isAllSelect = true;
			handleCalculatePrice();
		}
	}

	/** 计算价格 */
	const handleCalculatePrice = () => {
		let total : number = 0;
		let pointShowMoney : number = 0;
		let pointsSum : number = 0;
		let pointsMoneySum : number = 0;
		state.cartList.forEach((item : CartListType) => {
			if (item.select) {
				/** 商品总价 */
				total += item.nums * (item.products?.price * 10000);
				/** 积分能够兑换的价格 */
				pointShowMoney += item.nums * (item.products?.pointsDeduction * 10000);
				/** 需要多少积分 */
				pointsSum += shopConfigStore.config.pointDiscountedProportion * item.nums * (item.products?.pointsDeduction * 10000);
				/** 需要多少钱 */
				pointsMoneySum += ((item.products?.price - item.products?.pointsDeduction) * 10000) * item.nums;
			}
		})
		state.total = total / 10000;
		state.pointShowMoney = pointShowMoney / 10000;
		state.pointShowText = `${pointsSum / 10000}${shopConfigStore.config.pointShowName} +  ￥${pointsMoneySum <= 0 ? 0 : `${pointsMoneySum / 10000}`}`;

	}

	/** 点击管理 */
	const handleChangeManage = () => {
		state.isManage = !state.isManage;
	}

	/** 点击全选 然后计算价格 */
	const hanldeChangeAllSelect = () => {
		state.isAllSelect = !state.isAllSelect;
		state.cartList.forEach((item : CartListType) => {
			if (state.isAllSelect) {
				item['select'] = true;
			} else {
				item['select'] = false;
			}
		})
		nextTick(() => {
			handleCalculatePrice();
		})
	}

	/** 单个商品选择 */
	const hanldeSelectGoods = (index : number) => {
		state.cartList[index].select = !state.cartList[index].select;
		state.isAllSelect = state.cartList.every((item : CartListType) => item.select);
		nextTick(() => {
			handleCalculatePrice();
		})
	}

	/** 商品加减 */
	const handleChangeGoodsNum = async (e : any, item : CartListType) => {
		await setCartProductNum(item.productId, e.value);
		item.nums = e.value;
		handleCalculatePrice();
	}

	/** 单个删除 */
	const hanlderDeleteSingleGoods = (item : CartListType, index : number) => {
		hanldeShowModal({
			content: "您确定要删除此商品？",
			confirmFn: async () => {
				const data : Response<any> = await deleteGoodsSingle({ id: item.id });
				uni.showToast({
					title: data?.msg,
					duration: 3000,
					icon: "none"
				});
				if (data.status) {
					state.cartList.splice(index, 1);
					nextTick(() => {
						handleCalculatePrice();
					})
				}
			}
		})
	}

	/** 多个商品删除 */
	const hanlderDeleteSomeGoods = () => {
		let ids : Array<number> = [];
		state.cartList.forEach((item : CartListType, index : number) => {
			if (item.select) {
				ids.push(item.id)
			}
		});
		if (ids.length == 0) {
			handleShowToast('请选择要移除的商品');
			return;
		}
		hanldeShowModal({
			content: "您确定要移除已选中的商品？",
			confirmFn: async () => {
				const data : Response<any> = await deleteGoodsSome({ id: ids });
				handleShowToast(data?.msg);
				if (data.status) {
					ids.forEach((id : number) => {
						state.cartList.forEach((item : any, index : number) => {
							if (id == item.id) {
								state.cartList.splice(index, 1);
							}
						})
					})
					nextTick(() => {
						handleCalculatePrice();
					})
				}
			}
		})
	}

	/** 删除全部商品 */
	const hanlderDeleteAllGoods = () => {
		let ids : Array<number> = state.cartList.map((item : CartListType) => item.id);
		hanldeShowModal({
			content: "您确定要清空购物车？",
			confirmFn: async () => {
				const data : Response<any> = await deleteGoodsSome({ id: ids });
				handleShowToast(data?.msg);
				if (data.status) {
					state.cartList = [];
					state.total = 0;
					state.isManage = true;
				}
			}
		})
	}

	/** 去购买 */
	const handleGoToBuy = () => {
		const ids : Array<number> = state.cartList.filter(x => x.select).map(x => x.id);

		if (ids.length > 0) {
			handleRouteNavigateTo(`/pages/order/submit/submit?cartIds=${ids.join(',')}`)
		} else {
			handleShowToast('请选择要下单的商品');
		}
	}
</script>

<style lang="scss" scoped>
	@import './cart.scss';
</style>